<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <PageHeader back-text="返回合同列表" back-type="back" :title="contractInfo.contractName || '加载中...'" />

    <!-- 合同详情卡片 -->
    <ContractDetail :contract-info="contractInfo" />

    <!-- 已拆分项目卡片 -->
    <el-card class="box-card project-split-card mb-6">
      <template #header>
        <div class="flex justify-between items-center">
          <div class="card-header-left">
            <span class="title">已拆分项目</span>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="success" plain icon="Upload" @click="handleSubmitContract"
                  v-hasPermi="['project:info:edit']"
                  :disabled="!canSubmitContract || !checkContractStatus(contractInfo.contractStatus)" size="default">
                  提交合同拆分
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="addProjectRow" v-hasPermi="['project:info:add']"
                  :disabled="!checkContractStatus(contractInfo.contractStatus)" size="default">
                  新增项目
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-dropdown @command="handleMoreCommand" v-hasPermi="['project:info:import', 'project:info:export']">
                  <el-button :disabled="!checkContractStatus(contractInfo.contractStatus)" type="warning" plain
                    size="default">
                    导入导出
                    <el-icon class="el-icon--right">
                      <ArrowDown />
                    </el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="download-template">
                        <el-icon style="vertical-align: middle">
                          <Download />
                        </el-icon>
                        <span style="margin-left: 4px">下载模板</span>
                      </el-dropdown-item>
                      <el-dropdown-item command="import-data">
                        <el-icon style="vertical-align: middle">
                          <Upload />
                        </el-icon>
                        <span style="margin-left: 4px">导入数据</span>
                      </el-dropdown-item>
                      <el-dropdown-item command="export-data">
                        <el-icon style="vertical-align: middle">
                          <Download />
                        </el-icon>
                        <span style="margin-left: 4px">导出数据</span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </el-col>
              <el-col :span="1.5">
                <el-button type="info" plain icon="RefreshLeft" @click="handleRevertAuditFlow"
                  v-hasPermi="['project:info:audit']" :disabled="!canRevertAuditFlow" size="default">
                  重置审核流程
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <div style="display: flex; align-items: center; gap: 8px">
                  <el-select v-model="sortField" placeholder="请选择排序字段" style="width: 170px" clearable
                    @change="handleSortChange">
                    <el-option label="项目名称" value="proName" />
                    <el-option label="项目编号" value="proNumber" />
                    <el-option label="业主单位" value="ownerUnit" />
                    <el-option label="项目类型" value="proType" />
                    <el-option label="项目状态" value="proStatus" />
                    <el-option label="执行总裁" value="proPresidentsName" />
                    <el-option label="项目负责人" value="proLeadersName" />
                    <el-option label="创建时间" value="createTime" />
                    <el-option label="项目金额" value="proAmount" />
                  </el-select>
                  <el-button v-if="sortField" :icon="sortOrder === 'asc' ? 'ArrowUp' : 'ArrowDown'"
                    @click="toggleSortOrder" type="info" plain size="small"
                    :title="sortOrder === 'asc' ? '当前为正序，点击切换为逆序' : '当前为逆序，点击切换为正序'">
                    {{ sortOrder === 'asc' ? '正序' : '逆序' }}
                  </el-button>
                </div>
              </el-col>
            </el-row>
          </div>
          <div class="flex items-center" style="gap: 12px">
            <RefreshButton @refresh="refreshProjectList" />
            <ProjectStatusDisplay label="项目审核状态" :status-options="approval_commit_status"
              :status-value="contractInfo.proStatus || '0'" />
          </div>
        </div>
      </template>

      <!-- 项目录入表格 -->
      <el-table v-loading="loading" :data="projectList" border row-key="id" class="project-table"
        :row-class-name="tableRowClassName">
        <!-- 项目名称 -->
        <el-table-column label="项目名称" align="center" width="200" fixed="left">
          <template #default="scope">
            <el-input v-if="scope.row.isEditing" v-model="scope.row.proName" placeholder="请输入项目名称" />
            <span v-else>{{ scope.row.proName }}</span>
          </template>
        </el-table-column>

        <!-- 项目编号 -->
        <el-table-column label="项目编号" align="center" width="110">
          <template #default="scope">
            <el-input v-if="scope.row.isEditing" v-model="scope.row.proNumber" placeholder="请输入项目编号" />
            <span v-else>{{ scope.row.proNumber }}</span>
          </template>
        </el-table-column>

        <!-- 业主单位 -->
        <el-table-column label="业主单位" align="center" width="150">
          <template #default="scope">
            <el-input v-if="scope.row.isEditing" v-model="scope.row.ownerUnit" placeholder="请输入业主单位" />
            <span v-else>{{ scope.row.ownerUnit }}</span>
          </template>
        </el-table-column>

        <!-- 项目类型 -->
        <el-table-column label="项目类型" align="center" width="100">
          <template #default="scope">
            <el-select v-if="scope.row.isEditing" v-model="scope.row.proType" placeholder="请选择" style="width: 100%"
              filterable clearable>
              <el-option v-for="dict in project_type" :key="dict.value" :label="dict.label" :value="dict.value || ''" />
            </el-select>
            <dict-tag v-else :options="project_type" :value="scope.row.proType" />
          </template>
        </el-table-column>

        <!-- 工作内容 -->
        <el-table-column label="工作内容" align="left" width="400">
          <template #default="scope">
            <el-input v-if="scope.row.isEditing" v-model="scope.row.proContent" type="textarea" :rows="4"
              placeholder="请输入工作内容" />
            <el-tooltip v-else :content="scope.row.proContent" placement="top" :disabled="!scope.row.proContent">
              <span class="text-overflow">{{ scope.row.proContent }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- 执行总裁 -->
        <el-table-column label="执行总裁" align="center" width="120">
          <template #default="scope">
            <div v-if="scope.row.isEditing" class="inline-user-selector">
              <div class="selected-users-inline">
                <el-tag v-for="president in getSelectedPresidents(scope.row)" :key="president.userId" closable
                  @close="removeInlinePresident(scope.row, president)" type="primary">
                  {{ president.userName || president.nickName }}
                </el-tag>
              </div>
              <el-button type="primary" plain @click="openPresidentSelector(scope.row)" class="inline-select-btn"> 选择
              </el-button>
            </div>
            <span v-else>{{ scope.row.proPresidentsName }}</span>
          </template>
        </el-table-column>

        <!-- 项目负责人 -->
        <el-table-column label="项目负责人" align="center" width="120">
          <template #default="scope">
            <div v-if="scope.row.isEditing" class="inline-user-selector">
              <div class="selected-users-inline">
                <el-tag v-for="leader in getSelectedLeaders(scope.row)" :key="leader.userId" closable
                  @close="removeInlineLeader(scope.row, leader)" type="success">
                  {{ leader.userName || leader.nickName }}
                </el-tag>
              </div>
              <el-button type="success" plain @click="openLeaderSelector(scope.row)" class="inline-select-btn"> 选择
              </el-button>
            </div>
            <span v-else>{{ scope.row.proLeadersName }}</span>
          </template>
        </el-table-column>

        <!-- 项目金额 -->
        <el-table-column label="项目金额" align="center" width="150">
          <template #default="scope">
            <MoneyInput v-if="scope.row.isEditing" v-model="scope.row.proAmount" placeholder="请输入金额（保留两位小数）" />
            <span v-else>
              <span v-if="scope.row.proAmount">{{ formatAmount(scope.row.proAmount) }}元</span>
              <span v-else>-</span>
            </span>
          </template>
        </el-table-column>

        <!-- 项目金额备注 -->
        <el-table-column label="项目金额备注" align="left" width="200">
          <template #default="scope">
            <el-input v-if="scope.row.isEditing" v-model="scope.row.proAmountRemark" type="textarea" :rows="4"
              placeholder="请输入项目金额备注" />
            <el-tooltip v-else :content="scope.row.proAmountRemark" placement="top"
              :disabled="!scope.row.proAmountRemark">
              <span class="text-overflow">{{ scope.row.proAmountRemark || '-' }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- 项目状态 -->
        <el-table-column label="项目状态" align="center" width="100">
          <template #default="scope">
            <el-select v-if="scope.row.isEditing" v-model="scope.row.proStatus" placeholder="请选择" style="width: 100%"
              clearable>
              <el-option v-for="item in contract_status" :key="item.value" :label="item.label"
                :value="item.value || ''" />
            </el-select>
            <dict-tag v-else :options="contract_status" :value="scope.row.proStatus" />
          </template>
        </el-table-column>

        <!-- 备注 -->
        <el-table-column label="备注" align="left" width="150">
          <template #default="scope">
            <el-input v-if="scope.row.isEditing" v-model="scope.row.remark" type="textarea" :rows="4"
              placeholder="请输入备注" />
            <el-tooltip v-else :content="scope.row.remark" placement="top" :disabled="!scope.row.remark">
              <span class="text-overflow">{{ scope.row.remark }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- 创建人 -->
        <el-table-column label="创建人" align="center" prop="createBy" width="120" />

        <!-- 创建时间 -->
        <el-table-column label="创建时间" align="center" prop="createTime" width="120">
          <template #default="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>



        <!-- 回款节点 -->
        <el-table-column label="回款节点" width="100" fixed="right" align="center">
          <template #default="scope">
            <el-tooltip :content="getReceiveMoneyTooltip(scope.row)" placement="top">
              <el-button size="small" :type="getReceiveMoneyButtonType(scope.row)" plain icon="Edit"
                @click="openReceiveMoneyDialog(scope.row)" v-hasPermi="['project:receive:edit']"
                :disabled="!scope.row.id || !checkContractStatus(contractInfo.contractStatus)">
                编辑
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- 状态 -->
        <el-table-column label="保存状态" width="90" fixed="right" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.id ? 'success' : 'warning'">
              {{ scope.row.id ? '已保存' : '未保存' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="scope">
            <!-- 编辑模式下的操作按钮 -->
            <template v-if="scope.row.isEditing">
              <el-button size="small" type="primary" @click="saveProject(scope.row)" :loading="scope.row.saving"
                v-hasPermi="['project:info:add']">
                保存
              </el-button>

              <el-button size="small" type="danger" @click="cancelEdit(scope.row)" :disabled="scope.row.saving"> 取消
              </el-button>
            </template>
            <!-- 查看模式下的操作按钮 -->
            <template v-else>
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="editProject(scope.row)"
                  v-hasPermi="['project:info:edit']"
                  :disabled="!checkContractStatus(contractInfo.contractStatus)"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="danger" icon="Delete" @click="deleteProject(scope.row)"
                  v-hasPermi="['project:info:remove']"
                  :disabled="!checkContractStatus(contractInfo.contractStatus)"></el-button>
              </el-tooltip>
              <el-tooltip content="查看" placement="top">
                <el-button link type="info" icon="View" @click="viewProject(scope.row)"
                  v-hasPermi="['project:info:query']"></el-button>
              </el-tooltip>
            </template>
          </template>
        </el-table-column>

        <template #empty>
          <el-empty description="暂无项目数据" />
        </template>
      </el-table>

      <!-- 底部信息容器 - 使用组件 -->
      <ProjectBottomInfo :project-list="projectList" />
    </el-card>

    <!-- 项目详情编辑对话框 -->
    <el-dialog v-model="projectDetailVisible" title="项目详情编辑" width="900px" :close-on-click-modal="false">
      <el-form v-loading="projectDetailLoading" ref="projectDetailFormRef" :model="projectDetailForm"
        label-width="120px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="项目名称" prop="proName">
              <el-input v-model="projectDetailForm.proName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="项目编号" prop="proNumber">
              <el-input v-model="projectDetailForm.proNumber" placeholder="请输入项目编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="业主单位" prop="ownerUnit">
              <el-input v-model="projectDetailForm.ownerUnit" placeholder="请输入业主单位" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="项目类型" prop="proType">
              <el-select v-model="projectDetailForm.proType" placeholder="请选择项目类型" style="width: 100%" filterable
                clearable>
                <el-option v-for="dict in project_type" :key="dict.value" :label="dict.label"
                  :value="dict.value || ''" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="项目状态" prop="proStatus">
              <el-select v-model="projectDetailForm.proStatus" placeholder="请选择项目状态" style="width: 100%" clearable>
                <el-option v-for="item in contract_status" :key="item.value" :label="item.label"
                  :value="item.value || ''" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="工作内容" prop="proContent">
              <el-input v-model="projectDetailForm.proContent" type="textarea" :rows="6" placeholder="请输入工作内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="执行总裁" prop="proPresidentsName">
              <div class="user-selector-container">
                <div class="selected-users" v-if="getSelectedPresidentsForDetail().length > 0">
                  <el-tag v-for="president in getSelectedPresidentsForDetail()" :key="president.userId" closable
                    @close="removeDetailPresident(president)" type="primary"
                    style="margin-right: 8px; margin-bottom: 4px">
                    {{ president.userName || president.nickName }}
                  </el-tag>
                </div>
                <el-button type="primary" plain @click="openDetailPresidentSelector" style="width: 100%">
                  {{ getSelectedPresidentsForDetail().length > 0 ? '重新选择执行总裁' : '选择执行总裁' }}
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="项目负责人" prop="proLeadersName">
              <div class="user-selector-container">
                <div class="selected-users" v-if="getSelectedLeadersForDetail().length > 0">
                  <el-tag v-for="leader in getSelectedLeadersForDetail()" :key="leader.userId" closable
                    @close="removeDetailLeader(leader)" type="success" style="margin-right: 8px; margin-bottom: 4px">
                    {{ leader.userName || leader.nickName }}
                  </el-tag>
                </div>
                <el-button type="success" plain @click="openDetailLeaderSelector" style="width: 100%">
                  {{ getSelectedLeadersForDetail().length > 0 ? '重新选择项目负责人' : '选择项目负责人' }}
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="项目金额" prop="proAmount">
              <MoneyInput v-model="projectDetailForm.proAmount" placeholder="请输入金额（保留两位小数）" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="项目金额备注" prop="proAmountRemark">
              <el-input v-model="projectDetailForm.proAmountRemark" type="textarea" :rows="6" placeholder="请输入项目金额备注" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="projectDetailForm.remark" type="textarea" :rows="6" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 创建人、创建时间、修改人、修改时间 - 只读显示 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建人">
              <el-input v-model="projectDetailForm.createBy" style="width: 100%" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间">
              <el-input
                :value="projectDetailForm.createTime ? parseTime(projectDetailForm.createTime, '{y}-{m}-{d} {h}:{i}:{s}') : ''"
                style="width: 100%" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="修改人">
              <el-input v-model="projectDetailForm.updateBy" style="width: 100%" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="修改时间">
              <el-input
                :value="projectDetailForm.updateTime ? parseTime(projectDetailForm.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') : ''"
                style="width: 100%" readonly />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDetailEdit">取消</el-button>
          <el-button type="primary" @click="saveDetailProject" v-hasPermi="['project:info:edit']"
            :loading="projectDetailSaving">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 回款节点管理对话框 -->
    <el-dialog v-model="receiveMoneyDialogVisible" :title="`回款节点管理 - ${currentProjectForReceiveMoney?.proName || ''}`"
      width="900px" :close-on-click-modal="false">
      <div class="receive-money-container">
        <!-- 固定输入区域 -->
        <div class="receive-money-input-area">
          <div class="input-row">
            <el-input v-model="newNodeTitle" placeholder="输入回款节点名称" clearable @keyup.enter="addReceiveMoneyNode"
              style="flex: 1" />
            <el-input-number v-model="newNodeOrder" placeholder="节点序号" :min="1" style="flex: 0.5" />
            <div class="node-leader-selector" style="flex: 1">
              <div class="selected-leaders" v-if="newNodeLeadersName">
                <el-tag v-for="(leader, index) in getNewNodeLeaders()" :key="index" closable
                  @close="removeNewNodeLeader(index)" size="small" type="success"
                  style="margin-right: 4px; margin-bottom: 4px">
                  {{ leader }}
                </el-tag>
              </div>
              <el-button size="small" type="success" plain @click="openNewNodeLeaderSelector"
                :class="{ 'has-selection': newNodeLeadersName }" style="width: 100%">
                {{ newNodeLeadersName ? '重新选择负责人' : '选择收款负责人' }}
                <span style="color: #f56c6c; margin-left: 4px">*</span>
              </el-button>
            </div>
            <el-button type="primary" @click="addReceiveMoneyNode" v-hasPermi="['project:receive:add']"
              :disabled="!newNodeTitle.trim() || !newNodeLeadersId">
              添加
            </el-button>
          </div>
        </div>

        <!-- 节点列表 -->
        <div class="receive-money-list" v-if="currentProjectReceiveMoneyNodes.length > 0">
          <div class="nodes-table">
            <el-table :data="currentProjectReceiveMoneyNodes" border style="width: 100%">
              <el-table-column label="节点序号" align="center" width="80">
                <template #default="scope">
                  <el-input-number v-if="scope.row.isEditing" v-model="scope.row.receiveOrder" placeholder="序号" :min="1"
                    style="width: 120px" />
                  <span v-else>{{ scope.row.receiveOrder || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="付款节点" align="left" min-width="400">
                <template #default="scope">
                  <el-input v-if="scope.row.isEditing" v-model="scope.row.nodeTitle" placeholder="请输入节点名称" />
                  <span v-else>{{ scope.row.nodeTitle }}</span>
                </template>
              </el-table-column>

              <el-table-column label="收款负责人" align="center" width="120">
                <template #default="scope">
                  <div v-if="scope.row.isEditing" class="edit-leader-selector">
                    <div class="selected-leaders" v-if="scope.row.nodeLeadersName">
                      <el-tag v-for="(leader, index) in getEditNodeLeaders(scope.row)" :key="index" closable
                        @close="removeEditNodeLeader(scope.row, index)" size="small" type="success"
                        style="margin-right: 4px; margin-bottom: 4px">
                        {{ leader }}
                      </el-tag>
                    </div>
                    <el-button size="small" type="success" plain @click="openEditNodeLeaderSelector(scope.row)"
                      style="width: 100%">
                      {{ scope.row.nodeLeadersName ? '重新选择负责人' : '选择收款负责人' }}
                    </el-button>
                  </div>
                  <div v-else>
                    <div v-if="scope.row.nodeLeadersName" class="node-leaders-display">
                      <div class="selected-leaders-tags">
                        <el-tag v-for="(leader, index) in getNodeLeaders(scope.row)" :key="index" size="small"
                          type="success" style="margin: 2px">
                          {{ leader }}
                        </el-tag>
                      </div>
                    </div>
                    <span v-else class="text-gray-400">-</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" align="center">
                <template #default="scope">
                  <!-- 编辑模式 -->
                  <template v-if="scope.row.isEditing">
                    <el-button size="small" type="primary" @click="saveEditNode(scope.row)" :loading="scope.row.saving">
                      保存 </el-button>
                    <el-button size="small" type="danger" @click="cancelEditNode(scope.row)"
                      :disabled="scope.row.saving"> 取消 </el-button>
                  </template>
                  <!-- 查看模式 -->
                  <template v-else>
                    <el-button size="small" type="primary" v-hasPermi="['project:receive:edit']" icon="Edit"
                      @click="editNode(scope.row)" circle />
                    <el-button size="small" type="danger" v-hasPermi="['project:receive:delete']" icon="Delete"
                      @click="deleteNode(scope.row)" circle />
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <!-- 空状态提示 -->
        <div v-if="currentProjectReceiveMoneyNodes.length === 0" class="empty-state">
          <el-empty description="暂无回款节点" :image-size="80" />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeReceiveMoneyDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- UserSelector 组件 - 执行总裁选择 -->
    <UserSelector v-model:visible="showPresidentSelector" title="选择执行总裁"
      :selected-user-ids="currentEditingRow?.proPresidentsId"
      :selected-user-names="currentEditingRow?.proPresidentsName" :multiple="true"
      @confirmWithIds="handlePresidentConfirmWithIds" @cancel="handlePresidentCancel" />

    <!-- UserSelector 组件 - 项目负责人选择 -->
    <UserSelector v-model:visible="showLeaderSelector" title="选择项目负责人"
      :selected-user-ids="currentEditingRow?.proLeadersId" :selected-user-names="currentEditingRow?.proLeadersName"
      :multiple="true" @confirmWithIds="handleLeaderConfirmWithIds" @cancel="handleLeaderCancel" />

    <!-- UserSelector 组件 - 回款节点负责人选择 -->
    <UserSelector v-model:visible="showNodeLeaderSelector" title="选择收款负责人" :selected-user-ids="getNodeSelectedUserIds()"
      :selected-user-names="getNodeSelectedUserNames()" :multiple="true"
      @confirmWithIds="handleNodeLeaderConfirmWithIds" @cancel="handleNodeLeaderCancel" />

    <!-- UserSelector 组件 - 编辑节点负责人选择 -->
    <UserSelector v-model:visible="showEditNodeLeaderSelector" title="选择收款负责人"
      :selected-user-ids="currentEditingNode?.nodeLeadersId" :selected-user-names="currentEditingNode?.nodeLeadersName"
      :multiple="true" @confirmWithIds="handleEditNodeLeaderConfirmWithIds" @cancel="handleEditNodeLeaderCancel" />

    <!-- 审核流程组件 -->
    <ApprovalFlow v-model:visible="approvalFlowVisible" :business-type="businessType"
      :business-id="currentProjectForApproval?.id" :title="`合同拆分项目审核-${contractInfo.contractName || ''}`"
      @confirm="handleApprovalConfirm" @cancel="handleApprovalCancel" />

    <!-- 导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?contractId=' + contractInfo.id" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload">
          <UploadFilled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="handleImportTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { listProInfo, addProInfo, updateProInfo, delProInfo, getProInfo } from '@/api/project/init/proInfo';
import type { ProContractVO } from '@/api/project/init/contract/types';
import {
  saveReceiveMoneyNode,
  getReceiveMoneyNodesByProId,
  updateProReceiveMoney,
  removeReceiveMoneyNode
} from '@/api/project/receive/index';
import { getProContract, revertContractAuditFlow } from '@/api/project/init/contract/index';
import UserSelector from '@/components/UserSelector/index.vue';
import ApprovalFlow from '@/components/ApprovalFlow/index.vue';
import { MoneyInput, formatAmount } from '@/components/NumberInput';
import ProjectStatusDisplay from '@/views/project/components/ProjectStatusDisplay.vue';
import PageHeader from '@/views/project/components/PageHeader/index.vue';
import ContractDetail from '@/views/project/components/ContractDetail.vue';
import ProjectBottomInfo from '@/views/project/components/ProjectBottomInfo.vue';
import RefreshButton from '@/views/project/components/RefreshButton.vue';
import { globalHeaders } from '@/utils/request';
import { useRoute, useRouter } from 'vue-router';
import { checkContractStatus } from '@/utils/permission';
import { parseTime } from '@/utils/ruoyi';

const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

const { project_type, contract_status, approval_commit_status } = toRefs<any>(
  proxy?.useDict('project_type', 'contract_status', 'approval_commit_status')
);

// 合同信息
const contractInfo = ref<ProContractVO & { proStatus?: string }>({} as ProContractVO);

// 已拆分项目列表
const projectList = ref([]);
const loading = ref(false);

// UserSelector 相关
const showPresidentSelector = ref(false);
const showLeaderSelector = ref(false);
const currentEditingRow = ref<any>(null);

// 项目详情编辑相关
const projectDetailVisible = ref(false);
const projectDetailForm = ref<any>({
  proType: null,
  proStatus: '0'
});
const projectDetailLoading = ref(false);
const projectDetailSaving = ref(false);

// 审核流程相关
const approvalFlowVisible = ref(false);
const currentProjectForApproval = ref<any>(null);
const businessType = ref('CONTRACT-SPLIT-PROJECT');

// 导入相关
const uploadRef = ref();
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,

  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/pro/info/importData'
});

// 回款节点相关
const newNodeTitle = ref('');
const newNodeOrder = ref<number | null>(null);
const newNodeLeadersId = ref('');
const newNodeLeadersName = ref('');
const receiveMoneySaving = ref(false);
const receiveMoneyDialogVisible = ref(false);
const currentProjectForReceiveMoney = ref<any>(null);
const currentProjectReceiveMoneyNodes = ref([]);

// 回款节点负责人选择器相关
const showNodeLeaderSelector = ref(false);
const showEditNodeLeaderSelector = ref(false);
const currentEditingNode = ref(null);

// 计算是否可以提交合同
const canSubmitContract = computed(() => {
  return projectList.value.length > 0 && projectList.value.every((project) => project.id && !project.isEditing);
});

// 计算是否可以重置审核流程
const canRevertAuditFlow = computed(() => {
  // 只有合同已提交、审核中、审核通过、审核不过时才允许重置
  return contractInfo.value && ['1', '2', '3', '4'].includes(contractInfo.value.proStatus);
});

// 获取合同信息
const getContract = async (contractId) => {
  try {
    const res = await getProContract(contractId);
    if (res.data) {
      contractInfo.value = res.data;
    }
  } catch (error) {
    console.error('获取合同详情失败:', error);
    proxy?.$modal.msgError('获取合同详情失败');
  }
};

// 获取项目列表

const getProjectList = async (contractId) => {
  loading.value = true;
  try {
    const params: any = { contractId };
    // 处理排序参数
    if (sortField.value && sortOrder.value) {
      params.orderByColumn = sortField.value;
      params.isAsc = sortOrder.value;
    }
    const res = await listProInfo(params);
    projectList.value = (res.data || []).map((item) => ({
      ...item,
      isEditing: false,
      saving: false,
      originalData: null
    }));
  } catch (error) {
    console.error('获取项目列表失败:', error);
    proxy?.$modal.msgError('获取项目列表失败');
  } finally {
    loading.value = false;
  }
};

// 新增项目行
const addProjectRow = () => {
  const newProject = {
    id: undefined,
    contractId: contractInfo.value.id,
    proName: '',
    proNumber: '',
    ownerUnit: '',
    proType: null,
    proContent: '',
    proPresidentsId: '',
    proLeadersId: '',
    proPresidentsName: '',
    proLeadersName: '',
    proAmount: '',
    proAmountRemark: '',
    remark: '',
    proStatus: '0',
    commitStatus: '0',
    isEditing: true,
    saving: false,
    originalData: null
  };

  projectList.value.push(newProject);
};

// 编辑项目
const editProject = async (row: any) => {
  if (row.commitStatus === '2' || row.commitStatus === '3') {
    return;
  }

  try {
    const res = await getProInfo(row.id);
    const projectData = res.data;

    // 保存原始数据用于取消时恢复
    row.originalData = JSON.parse(JSON.stringify(projectData));

    // 更新行数据
    Object.assign(row, projectData);
    row.isEditing = true;
    row.saving = false;
  } catch (error) {
    console.error('获取项目详情失败:', error);
    proxy?.$modal.msgError('获取项目详情失败');
  }
};

// 保存未保存的编辑项
const saveUnsavedEditingItems = () => {
  return projectList.value
    .filter((item) => item.isEditing && !item.saving)
    .map((item) => ({
      ...item,
      // 深拷贝以避免引用问题
      originalData: item.originalData ? JSON.parse(JSON.stringify(item.originalData)) : null
    }));
};

// 恢复未保存的编辑项
const restoreUnsavedEditingItems = (unsavedItems) => {
  if (unsavedItems.length === 0) return;

  // 将未保存的编辑项重新添加到项目列表中
  unsavedItems.forEach((unsavedItem) => {
    // 检查是否是新增项（没有id）
    if (!unsavedItem.id) {
      // 检查是否已经存在相同的新增项（通过临时标识符或其他唯一属性）
      const existingNewItem = projectList.value.find(
        (item) => !item.id && item.proName === unsavedItem.proName && item.proNumber === unsavedItem.proNumber && item.isEditing
      );

      if (!existingNewItem) {
        // 新增项直接添加到列表末尾
        projectList.value.push(unsavedItem);
      }
    } else {
      // 编辑项需要找到对应的项目并替换为编辑状态
      const existingIndex = projectList.value.findIndex((item) => item.id === unsavedItem.id);
      if (existingIndex > -1) {
        // 保持编辑状态
        projectList.value[existingIndex] = unsavedItem;
      }
    }
  });
};

// 保存项目 - 优化逻辑，保留其他编辑项状态
const saveProject = async (row: any) => {
  row.saving = true;
  try {
    const submitData = { ...row };
    delete submitData.isEditing;
    delete submitData.saving;
    delete submitData.originalData;

    // 将 createBy/createTime/updateBy/updateTime 设置为 null，避免 BO 继承 BaseEntity 时的转换问题
    submitData.createBy = null;
    submitData.createTime = null;
    submitData.updateBy = null;
    submitData.updateTime = null;

    // 处理金额字段
    submitData.proAmount = submitData.proAmount ? parseFloat(submitData.proAmount) : null;

    // 保存其他正在编辑的项目状态（排除当前保存的项目）
    const unsavedItems = projectList.value
      .filter((item) => item.isEditing && !item.saving && item !== row)
      .map((item) => ({
        ...item,
        // 深拷贝以避免引用问题
        originalData: item.originalData ? JSON.parse(JSON.stringify(item.originalData)) : null
      }));

    if (!submitData.id) {
      submitData.proStatus = '0';
      const res = await addProInfo(submitData);
      row.id = res.data?.id || row.id;
      proxy?.$modal.msgSuccess('新增成功');
    } else {
      await updateProInfo(submitData);
      proxy?.$modal.msgSuccess('修改成功');
    }

    row.isEditing = false;
    row.originalData = null;

    // 刷新项目列表和合同信息
    await getProjectList(contractInfo.value.id);
    await getContract(contractInfo.value.id);

    // 恢复其他正在编辑的项目状态
    restoreUnsavedEditingItems(unsavedItems);
  } catch (error) {
    console.error('保存项目失败:', error);
    proxy?.$modal.msgError('操作失败');
  } finally {
    row.saving = false;
  }
};

// 取消编辑
const cancelEdit = (row: any) => {
  if (row.originalData) {
    Object.assign(row, row.originalData);
    row.isEditing = false;
    row.originalData = null;
  } else {
    const index = projectList.value.findIndex((item) => item === row);
    if (index > -1) {
      projectList.value.splice(index, 1);
    }
  }
};

// 删除项目
const deleteProject = async (row: any) => {
  try {
    // 检查是否有正在编辑的项目（排除当前要删除的项）
    const hasEditingItems = projectList.value.some((item) => item.isEditing && item !== row);
    if (hasEditingItems) {
      proxy?.$modal.msgWarning('当前有项目正在编辑中，请先保存或取消编辑后再进行删除操作');
      return;
    }

    if (!row.id) {
      const index = projectList.value.findIndex((item) => item === row);
      if (index > -1) {
        projectList.value.splice(index, 1);
      }
      return;
    }

    await proxy?.$modal.confirm(`确定删除项目"${row.proName}"吗？`);

    await delProInfo(row.id);
    proxy?.$modal.msgSuccess('删除成功');

    // 刷新项目列表和合同信息
    await getProjectList(contractInfo.value.id);
    await getContract(contractInfo.value.id);
  } catch (error) {
    console.error('删除项目失败:', error);
  }
};

// 刷新项目列表
const refreshProjectList = async () => {
  if (contractInfo.value.id) {
    // 检查是否有正在编辑的项目
    const hasEditingItems = projectList.value.some((item) => item.isEditing);
    if (hasEditingItems) {
      proxy?.$modal.msgWarning('当前有项目正在编辑中，请先保存或取消编辑后再进行刷新操作');
      return;
    }

    await getProjectList(contractInfo.value.id);
  }
};

// 解析用户信息的通用函数
const parseUserInfo = (userIds: string, userNames: string) => {
  if (!userIds || userIds === '') {
    return [];
  }

  if (userNames) {
    const ids = userIds
      .split(',')
      .map((id) => id.trim())
      .filter((id) => id);
    const names = userNames
      .split(',')
      .map((name) => name.trim())
      .filter((name) => name);

    if (ids.length === names.length) {
      return ids.map((id, index) => ({
        userId: id,
        userName: names[index],
        nickName: names[index]
      }));
    }
  }

  return [];
};

// 获取选中的执行总裁
const getSelectedPresidents = (row: any) => {
  return parseUserInfo(row.proPresidentsId, row.proPresidentsName);
};

// 获取选中的项目负责人
const getSelectedLeaders = (row: any) => {
  return parseUserInfo(row.proLeadersId, row.proLeadersName);
};

// 打开执行总裁选择器
const openPresidentSelector = (row: any) => {
  currentEditingRow.value = row;
  showPresidentSelector.value = true;
};

// 打开项目负责人选择器
const openLeaderSelector = (row: any) => {
  currentEditingRow.value = row;
  showLeaderSelector.value = true;
};

// 通用移除用户函数
const removeUser = (row: any, user: any, userIdsField: string, userNamesField: string) => {
  const currentUsers = parseUserInfo(row[userIdsField], row[userNamesField]);
  const newUsers = currentUsers.filter((u) => u.userId !== user.userId);

  row[userIdsField] = newUsers.length > 0 ? newUsers.map((u) => u.userId).join(',') : '';
  row[userNamesField] = newUsers.length > 0 ? newUsers.map((u) => u.nickName || u.userName).join(',') : '';
};

// 移除内联执行总裁
const removeInlinePresident = (row: any, president: any) => {
  removeUser(row, president, 'proPresidentsId', 'proPresidentsName');
};

// 移除内联项目负责人
const removeInlineLeader = (row: any, leader: any) => {
  removeUser(row, leader, 'proLeadersId', 'proLeadersName');
};

// 通用用户选择确认处理
const handleUserConfirm = (data, userIdsField: string, userNamesField: string) => {
  if (currentEditingRow.value) {
    currentEditingRow.value[userIdsField] = data.userIds || '';
    currentEditingRow.value[userNamesField] = data.userNames || '';
  }
  currentEditingRow.value = null;
};

// 执行总裁选择确认
const handlePresidentConfirmWithIds = (data) => {
  handleUserConfirm(data, 'proPresidentsId', 'proPresidentsName');
  showPresidentSelector.value = false;
};

// 执行总裁选择取消
const handlePresidentCancel = () => {
  showPresidentSelector.value = false;
  currentEditingRow.value = null;
};

// 项目负责人选择确认
const handleLeaderConfirmWithIds = (data) => {
  handleUserConfirm(data, 'proLeadersId', 'proLeadersName');
  showLeaderSelector.value = false;
};

// 项目负责人选择取消
const handleLeaderCancel = () => {
  showLeaderSelector.value = false;
  currentEditingRow.value = null;
};

// 通用字符串分割处理函数
const parseCommaString = (str: string) => {
  if (!str) return [];
  return str
    .split(',')
    .map((item) => item.trim())
    .filter((item) => item);
};

// 表格行样式
const tableRowClassName = ({ row }: { row: any }) => {
  return row.isEditing ? 'editing-row' : '';
};

// 获取回款节点按钮类型
const getReceiveMoneyButtonType = (row: any) => {
  return row.hasReceiveNode === '1' ? 'success' : 'warning'; // 有回款节点用绿色，没有用橙色
};

// 获取回款节点提示文本
const getReceiveMoneyTooltip = (row: any) => {
  if (!row.id) return '回款节点（请先保存项目）';
  return row.hasReceiveNode === '1' ? '回款节点（已设置）' : '回款节点（点击管理）';
};

onMounted(async () => {
  const contractId = route.params.contractId;
  if (contractId) {
    try {
      await Promise.all([getContract(contractId), getProjectList(contractId)]);
    } catch (error) {
      console.error('初始化数据失败:', error);
      proxy?.$modal.msgError('加载数据失败，请刷新页面重试');
    }
  } else {
    proxy?.$modal.msgError('缺少合同ID参数');
    router.push('/project/init/proInfo');
  }
});

// 提交合同拆分
const handleSubmitContract = async () => {
  try {
    if (!canSubmitContract.value) {
      proxy?.$modal.msgWarning('请确保所有项目已保存且没有正在编辑的项目');
      return;
    }

    currentProjectForApproval.value = {
      id: contractInfo.value.id,
      proName: contractInfo.value.contractName || '合同拆分项目'
    };
    approvalFlowVisible.value = true;
  } catch (error) {
    console.error('打开审核流程失败:', error);
    proxy?.$modal.msgError('打开审核流程失败');
  }
};

// 审核流程确认回调
const handleApprovalConfirm = async () => {
  try {
    proxy?.$modal.msgSuccess('审核流程提交成功');
    approvalFlowVisible.value = false;
    currentProjectForApproval.value = null;
    // 刷新合同详情和项目列表
    await Promise.all([getContract(contractInfo.value.id), getProjectList(contractInfo.value.id)]);
  } catch (error) {
    console.error('审核流程提交失败:', error);
    proxy?.$modal.msgError('审核流程提交失败');
  }
};

// 审核流程取消回调
const handleApprovalCancel = () => {
  approvalFlowVisible.value = false;
  currentProjectForApproval.value = null;
};

// 查看项目详情
const viewProject = async (row) => {
  projectDetailVisible.value = true;
  projectDetailForm.value = {
    proType: null,
    proStatus: '0'
  };
  projectDetailLoading.value = true;
  try {
    const res = await getProInfo(row.id);
    projectDetailForm.value = { ...res.data };
  } catch (error) {
    console.error('获取项目信息失败:', error);
    proxy?.$modal.msgError('获取项目信息失败');
    projectDetailVisible.value = false;
  } finally {
    projectDetailLoading.value = false;
  }
};

// 获取详情对话框中选中的执行总裁
const getSelectedPresidentsForDetail = () => {
  return parseUserInfo(projectDetailForm.value.proPresidentsId, projectDetailForm.value.proPresidentsName);
};

// 获取详情对话框中选中的项目负责人
const getSelectedLeadersForDetail = () => {
  return parseUserInfo(projectDetailForm.value.proLeadersId, projectDetailForm.value.proLeadersName);
};

// 移除详情对话框中的执行总裁
const removeDetailPresident = (president) => {
  removeUser(projectDetailForm.value, president, 'proPresidentsId', 'proPresidentsName');
};

// 移除详情对话框中的项目负责人
const removeDetailLeader = (leader) => {
  removeUser(projectDetailForm.value, leader, 'proLeadersId', 'proLeadersName');
};

// 打开详情对话框中的执行总裁选择器
const openDetailPresidentSelector = () => {
  currentEditingRow.value = projectDetailForm.value;
  showPresidentSelector.value = true;
};

// 打开详情对话框中的项目负责人选择器
const openDetailLeaderSelector = () => {
  currentEditingRow.value = projectDetailForm.value;
  showLeaderSelector.value = true;
};

// 保存详情对话框中的项目
const saveDetailProject = async () => {
  projectDetailSaving.value = true;
  try {
    const submitData = { ...projectDetailForm.value };

    // 将 createBy、createTime、updateBy、updateTime 设置为 null，避免 BO 继承 BaseEntity 时的转换问题
    submitData.createBy = null;
    submitData.createTime = null;
    submitData.updateBy = null;
    submitData.updateTime = null;

    // 处理金额字段
    submitData.proAmount = submitData.proAmount ? parseFloat(submitData.proAmount) : null;

    await updateProInfo(submitData);
    proxy?.$modal.msgSuccess('修改成功');

    projectDetailVisible.value = false;
    projectDetailForm.value = {
      proType: null,
      proStatus: '0'
    };

    await getProjectList(contractInfo.value.id);
    await getContract(contractInfo.value.id);
  } catch (error) {
    console.error('保存项目失败:', error);
    proxy?.$modal.msgError('操作失败');
  } finally {
    projectDetailSaving.value = false;
  }
};

// 取消详情对话框编辑
const cancelDetailEdit = () => {
  projectDetailVisible.value = false;
  projectDetailForm.value = {
    proType: null,
    proStatus: '0'
  };
};

// 打开回款节点管理对话框
const openReceiveMoneyDialog = async (row: any) => {
  currentProjectForReceiveMoney.value = row;
  receiveMoneyDialogVisible.value = true;

  // 加载回款节点列表
  await loadCurrentProjectReceiveMoneyNodes();

  // 清空输入框
  newNodeTitle.value = '';
  // 设置默认序号为当前节点数量+1
  newNodeOrder.value = currentProjectReceiveMoneyNodes.value.length + 1;
  newNodeLeadersId.value = '';
  newNodeLeadersName.value = '';
};

// 关闭回款节点管理对话框
const closeReceiveMoneyDialog = () => {
  receiveMoneyDialogVisible.value = false;
  currentProjectForReceiveMoney.value = null;
  currentProjectReceiveMoneyNodes.value = [];
  newNodeTitle.value = '';
  newNodeOrder.value = null;
  newNodeLeadersId.value = '';
  newNodeLeadersName.value = '';
};

// 添加回款节点
const addReceiveMoneyNode = async () => {
  const title = newNodeTitle.value.trim();

  if (!title) {
    proxy?.$modal.msgWarning('请输入节点名称');
    return;
  }

  if (!newNodeLeadersId.value || !newNodeLeadersName.value) {
    proxy?.$modal.msgWarning('请选择收款负责人');
    return;
  }

  // 检查是否已存在相同节点
  const exists = currentProjectReceiveMoneyNodes.value.some((node) => node.nodeTitle?.trim() === title);
  if (exists) {
    proxy?.$modal.msgWarning(`节点"${title}"已存在`);
    return;
  }

  try {
    const nodeData = {
      proId: currentProjectForReceiveMoney.value.id,
      nodeTitle: title,
      totalAmount: 0,
      receivedAmount: 0,
      surplusAmount: 0,
      isArrive: '0',
      remark: '',
      nodeLeadersId: newNodeLeadersId.value,
      nodeLeadersName: newNodeLeadersName.value,
      receiveOrder: newNodeOrder.value
    };

    await saveReceiveMoneyNode(nodeData);
    proxy?.$modal.msgSuccess('节点添加成功');

    // 清空输入框
    newNodeTitle.value = '';
    newNodeLeadersId.value = '';
    newNodeLeadersName.value = '';

    // 重新加载节点列表
    await loadCurrentProjectReceiveMoneyNodes();

    // 重新设置默认序号为当前节点数量+1
    newNodeOrder.value = currentProjectReceiveMoneyNodes.value.length + 1;

    // 刷新项目列表以更新回款节点状态
    await getProjectList(contractInfo.value.id);
  } catch (error) {
    console.error('添加节点失败:', error);
    proxy?.$modal.msgError('添加节点失败');
  }
};

// 保存未保存的编辑项
const saveUnsavedEditingNodes = () => {
  return currentProjectReceiveMoneyNodes.value
    .filter((node) => node.isEditing && !node.saving)
    .map((node) => ({
      ...node,
      // 深拷贝以避免引用问题
      originalData: node.originalData ? JSON.parse(JSON.stringify(node.originalData)) : null
    }));
};

// 恢复未保存的编辑项
const restoreUnsavedEditingNodes = (unsavedNodes) => {
  if (unsavedNodes.length === 0) return;

  // 将未保存的编辑项重新添加到节点列表中
  unsavedNodes.forEach((unsavedNode) => {
    // 检查是否是新增项（没有id）
    if (!unsavedNode.id) {
      // 检查是否已经存在相同的新增项
      const existingNewNode = currentProjectReceiveMoneyNodes.value.find(
        (node) => !node.id && node.nodeTitle === unsavedNode.nodeTitle && node.isEditing
      );

      if (!existingNewNode) {
        // 新增项直接添加到列表末尾
        currentProjectReceiveMoneyNodes.value.push(unsavedNode);
      }
    } else {
      // 编辑项需要找到对应的节点并替换为编辑状态
      const existingIndex = currentProjectReceiveMoneyNodes.value.findIndex((node) => node.id === unsavedNode.id);
      if (existingIndex > -1) {
        // 保持编辑状态
        currentProjectReceiveMoneyNodes.value[existingIndex] = unsavedNode;
      }
    }
  });
};

// 重新加载当前项目的回款节点
const loadCurrentProjectReceiveMoneyNodes = async () => {
  try {
    // 保存其他正在编辑的节点状态（排除当前保存的节点）
    const unsavedNodes = currentProjectReceiveMoneyNodes.value
      .filter((node) => node.isEditing && !node.saving)
      .map((node) => ({
        ...node,
        // 深拷贝以避免引用问题
        originalData: node.originalData ? JSON.parse(JSON.stringify(node.originalData)) : null
      }));

    const res = await getReceiveMoneyNodesByProId(currentProjectForReceiveMoney.value.id);
    currentProjectReceiveMoneyNodes.value = (res.data || []).map((node) => ({
      ...node,
      isEditing: false,
      saving: false,
      originalData: null
    }));

    // 恢复其他正在编辑的节点状态
    restoreUnsavedEditingNodes(unsavedNodes);
  } catch (error) {
    console.error('获取回款节点失败:', error);
  }
};

// 编辑节点
const editNode = (node) => {
  // 保存原始数据用于取消时恢复
  node.originalData = JSON.parse(JSON.stringify(node));
  node.isEditing = true;
  node.saving = false;
};

// 保存编辑的节点
const saveEditNode = async (node) => {
  node.saving = true;
  try {
    const nodeData = {
      id: node.id,
      proId: node.proId,
      nodeTitle: node.nodeTitle,
      totalAmount: 0,
      receivedAmount: 0,
      surplusAmount: 0,
      nodeLeadersId: node.nodeLeadersId,
      nodeLeadersName: node.nodeLeadersName,
      remark: node.remark || '',
      receiveOrder: node.receiveOrder
    };

    await updateProReceiveMoney(nodeData);
    proxy?.$modal.msgSuccess('节点修改成功');

    node.isEditing = false;
    node.originalData = null;

    // 重新加载节点列表
    await loadCurrentProjectReceiveMoneyNodes();

    // 刷新项目列表以更新回款节点状态
    await getProjectList(contractInfo.value.id);
  } catch (error) {
    console.error('保存节点失败:', error);
    proxy?.$modal.msgError('保存节点失败');
  } finally {
    node.saving = false;
  }
};

// 取消编辑节点
const cancelEditNode = (node) => {
  if (node.originalData) {
    Object.assign(node, node.originalData);
    node.isEditing = false;
    node.originalData = null;
  }
};

// 删除节点
const deleteNode = async (node) => {
  try {
    await proxy?.$modal.confirm(`确定删除节点"${node.nodeTitle}"吗？`);
    await removeReceiveMoneyNode(node.id);
    proxy?.$modal.msgSuccess('节点删除成功');

    // 重新加载节点列表
    await loadCurrentProjectReceiveMoneyNodes();

    // 调整新增节点的序号为当前节点数量+1
    newNodeOrder.value = currentProjectReceiveMoneyNodes.value.length + 1;

    // 刷新项目列表以更新回款节点状态
    await getProjectList(contractInfo.value.id);
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除节点失败:', error);
      proxy?.$modal.msgError('删除节点失败');
    }
  }
};

// 获取编辑节点的负责人列表
const getEditNodeLeaders = (node) => {
  return parseCommaString(node.nodeLeadersName);
};

// 移除编辑节点的负责人
const removeEditNodeLeader = (node, index) => {
  const leaderIds = parseCommaString(node.nodeLeadersId);
  const leaderNames = parseCommaString(node.nodeLeadersName);

  if (index >= 0 && index < leaderIds.length && index < leaderNames.length) {
    leaderIds.splice(index, 1);
    leaderNames.splice(index, 1);

    node.nodeLeadersId = leaderIds.join(',');
    node.nodeLeadersName = leaderNames.join(',');
  }
};

// 打开编辑节点的负责人选择器
const openEditNodeLeaderSelector = (node) => {
  currentEditingNode.value = node;
  showEditNodeLeaderSelector.value = true;
};

// 处理编辑节点负责人选择确认
const handleEditNodeLeaderConfirmWithIds = (data) => {
  if (currentEditingNode.value) {
    currentEditingNode.value.nodeLeadersId = data.userIds || '';
    currentEditingNode.value.nodeLeadersName = data.userNames || '';
  }
  showEditNodeLeaderSelector.value = false;
  currentEditingNode.value = null;
};

// 处理编辑节点负责人选择取消
const handleEditNodeLeaderCancel = () => {
  showEditNodeLeaderSelector.value = false;
  currentEditingNode.value = null;
};

// 获取新节点负责人列表
const getNewNodeLeaders = () => {
  return parseCommaString(newNodeLeadersName.value);
};

// 获取节点负责人列表
const getNodeLeaders = (node: any) => {
  return parseCommaString(node.nodeLeadersName);
};

// 移除新节点负责人
const removeNewNodeLeader = (index: number) => {
  const leaderIds = parseCommaString(newNodeLeadersId.value);
  const leaderNames = parseCommaString(newNodeLeadersName.value);

  if (index >= 0 && index < leaderIds.length && index < leaderNames.length) {
    leaderIds.splice(index, 1);
    leaderNames.splice(index, 1);

    newNodeLeadersId.value = leaderIds.join(',');
    newNodeLeadersName.value = leaderNames.join(',');
  }
};

// 打开新节点负责人选择器
const openNewNodeLeaderSelector = () => {
  showNodeLeaderSelector.value = true;
};

// 获取节点选择的用户ID（仅用于新增节点）
const getNodeSelectedUserIds = () => {
  return newNodeLeadersId.value;
};

// 获取节点选择的用户姓名（仅用于新增节点）
const getNodeSelectedUserNames = () => {
  return newNodeLeadersName.value;
};

// 处理节点负责人选择确认
const handleNodeLeaderConfirmWithIds = (data) => {
  newNodeLeadersId.value = data.userIds || '';
  newNodeLeadersName.value = data.userNames || '';
  showNodeLeaderSelector.value = false;
};

// 处理节点负责人选择取消
const handleNodeLeaderCancel = () => {
  showNodeLeaderSelector.value = false;
};

// 处理更多命令
const handleMoreCommand = (command) => {
  switch (command) {
    case 'download-template':
      handleImportTemplate();
      break;
    case 'import-data':
      handleImport();
      break;
    case 'export-data':
      handleExport();
      break;
    default:
      break;
  }
};

/**
 * 下载导入模板
 */
const handleImportTemplate = () => {
  proxy?.download('pro/info/importTemplate', {}, `project_info_template_${new Date().getTime()}.xlsx`);
};

/**
 * 导出数据
 */
const handleExport = () => {
  const queryParams = {
    contractId: contractInfo.value.id
  };
  proxy?.download('pro/info/export', queryParams, `project_info_${new Date().getTime()}.xlsx`);
};

/**
 * 导入按钮操作
 */
const handleImport = () => {
  if (!contractInfo.value.id) {
    proxy?.$modal.msgError('合同ID不能为空');
    return;
  }
  upload.title = '项目信息导入';
  upload.open = true;
  upload.isUploading = false;

  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
};

/**
 * 文件上传中处理
 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

/**
 * 文件上传成功处理
 */
const handleFileSuccess = (response: any) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.clearFiles();

  // 导出结果弹出
  ElMessageBox.alert(response.msg, '导入结果', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确定',
    type: 'info'
  });
  // 重新获取项目列表和合同详情
  getProjectList(contractInfo.value.id);
  getContract(contractInfo.value.id);
};

/**
 * 提交上传文件
 */
const submitFileForm = () => {
  uploadRef.value?.submit();
};

// 重置审核流程
const handleRevertAuditFlow = async () => {
  if (!contractInfo.value.id) {
    proxy?.$modal.msgError('合同ID不能为空');
    return;
  }
  try {
    await proxy?.$modal.confirm('确定要重置该合同的审核流程吗？重置后将回到未提交状态。');
    await revertContractAuditFlow(contractInfo.value.id);
    proxy?.$modal.msgSuccess('重置审核流程成功');
    await getContract(contractInfo.value.id);
  } catch (error) {
    if (error !== 'cancel') {
      proxy?.$modal.msgError('重置审核流程失败');
    }
  }
};

// 移除：重置回款审核流程逻辑（不再需要）

// 排序字段
const sortField = ref('');
// 排序顺序
const sortOrder = ref('asc');

// 处理排序变化
const handleSortChange = () => {
  // 如果选择了排序字段但没有选择排序顺序，则设置默认值
  if (sortField.value && !sortOrder.value) {
    sortOrder.value = 'asc';
  }
  // 刷新项目列表
  if (contractInfo.value.id) {
    getProjectList(contractInfo.value.id);
  }
};

// 切换排序顺序
const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
  // 刷新项目列表
  if (contractInfo.value.id) {
    getProjectList(contractInfo.value.id);
  }
};
</script>

<style scoped>
/* 页面容器样式 */
.app-container {
  padding: 20px;
}

/* 项目拆分卡片样式 */
.project-split-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 12px;
}

/* 编辑状态行背景色 */
:deep(.editing-row) {
  background-color: var(--el-color-primary-light-9);
}

:deep(.editing-row td) {
  background-color: var(--el-color-primary-light-9) !important;
}

/* 项目表格样式 */
.project-table {
  width: 100%;
}

.project-table :deep(.el-table__cell) {
  padding: 8px 0;
}

/* 文本溢出处理 */
.text-overflow {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  vertical-align: top;
}

/* 内联用户选择器样式 */
.inline-user-selector {
  display: flex;
  flex-direction: column;
  gap: 4px;
  width: 100%;
}

.selected-users-inline {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  min-height: 20px;
}

.inline-select-btn {
  align-self: flex-start;
  padding: 4px 8px;
  font-size: 12px;
  height: auto;
  min-height: 24px;
}

/* 表格内的小尺寸组件调整 */
.project-table :deep(.el-input__wrapper) {
  min-height: 28px;
}

.project-table :deep(.el-select .el-input__wrapper) {
  min-height: 28px;
}

.project-table :deep(.el-date-editor.el-input) {
  width: 100%;
}

.project-table :deep(.el-date-editor .el-input__wrapper) {
  min-height: 28px;
}

.project-table :deep(.el-textarea__inner) {
  min-height: 60px;
  resize: vertical;
}

/* 小尺寸标签样式 */
.project-table :deep(.el-tag--small) {
  height: 20px;
  line-height: 18px;
  font-size: 11px;
  padding: 0 4px;
}

/* 操作按钮组样式 */
.project-table :deep(.el-button + .el-button) {
  margin-left: 4px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .inline-user-selector {
    min-width: 120px;
  }

  .selected-users-inline {
    max-height: 60px;
    overflow-y: auto;
  }
}

/* 响应式调整 */
.card-header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.card-header-left .title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-header-left .el-button {
  transition: all 0.2s ease;
}

.card-header-left .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* ==================== 回款节点样式 ==================== */

/* 回款节点容器样式 */
.receive-money-container {
  width: 100%;
  border: 1px solid var(--el-border-color);
  border-radius: 8px;
  background-color: var(--el-fill-color-blank);
  overflow: hidden;
}

/* 输入区域样式 */
.receive-money-input-area {
  padding: 20px;
  background-color: var(--el-fill-color-lighter);
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.input-row {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 节点列表样式 */
.receive-money-list {
  padding: 20px;
}

/* 空状态样式 */
.empty-state {
  padding: 40px 20px;
  text-align: center;
  border-top: 1px solid var(--el-border-color-lighter);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .receive-money-input-area {
    padding: 16px;
  }

  .receive-money-list {
    padding: 16px;
  }

  .input-row {
    flex-direction: column;
    gap: 8px;
  }

  .input-row .el-input {
    width: 100%;
  }

  .input-row .el-button {
    width: 100%;
  }

  .selected-leaders,
  .selected-leaders-tags {
    max-height: 80px;
    overflow-y: auto;
  }

  .node-leaders-display {
    min-width: 0;
  }
}

/* ==================== 回款节点对话框样式 ==================== */

/* 节点表格样式 */
.nodes-table {
  margin-bottom: 20px;
}

/* 节点负责人选择器样式 */
.node-leader-selector {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.selected-leaders {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  min-height: 20px;
  margin-bottom: 4px;
  max-width: 100%;
}

.selected-leaders-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 4px;
  max-width: 100%;
}

.node-leaders-display {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

.node-leaders-display .selected-leaders-tags {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  gap: 4px;
  max-width: 100%;
}

/* 对话框内的回款节点输入行样式调整 */
.receive-money-container .input-row {
  display: flex;
  gap: 12px;
  align-items: center;
}

.receive-money-container .input-row .el-input {
  flex: 1;
}

.receive-money-container .input-row .el-button {
  flex-shrink: 0;
}

/* 项目详情对话框中的用户选择器样式 */
.user-selector-container {
  width: 100%;
}

.user-selector-container .selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
  min-height: 20px;
}

.user-selector-container .el-button {
  width: 100%;
}
</style>
